import {Component, Input, OnInit} from '@angular/core';
import {TableFindModel} from '../table-find/table-find.model';
import {CommonTool} from '../common.tool';

@Component({
  selector: 'app-list-find',
  templateUrl: './list-find.component.html',
  styleUrls: ['./list-find.component.scss']
})
export class ListFindComponent implements OnInit {

  @Input()
  public tableFindModel: TableFindModel;
  public COMMON_TYPE = TableFindModel.COMMON_TYPE;
  public commonTool = CommonTool;
  public pagingDataModels: Array<any>;
  public rule;

  constructor() {
  }

  ngOnInit() {
    const that = this;
    const config = this.tableFindModel.config;
    // 前端分页
    if (config.openPaging && config.frontPaging) {
      that.pagingDataModels = [];
      this.tableFindModel.dataModels.forEach(data => {
        that.pagingDataModels.push(data);
      });
      that.frontPaging();
    }
  }

  /**
   * 前端分页
   */
  public frontPaging() {
    const config = this.tableFindModel.config;
    config.paging.total = this.pagingDataModels.length;
    if (config.paging.total <= 0) {
      config.paging.total = 1;
    }
    if (CommonTool.notNull(config.paging)) {
      let index = 0;
      this.tableFindModel.dataModels = [];
      for (let i = (config.paging.current - 1) * config.paging.size; i < this.pagingDataModels.length; i++) {
        if (index === config.paging.size) {
          break;
        }
        this.tableFindModel.dataModels.push(JSON.parse(JSON.stringify(this.pagingDataModels[i])));
        index++;
      }
    }
  }

  /**
   * 修改current
   */
  public indexChange(e) {
    // 前端分页
    const config = this.tableFindModel.config;
    if (config.openPaging && config.frontPaging) {
      if (CommonTool.notNull(e)) {
        config.paging.current = e;
      }
      this.frontPaging();
    } else {
      this.tableFindModel.paging(e, null);
    }
  }

  /**
   * 修改size
   */
  public sizeChange(e) {
    this.tableFindModel.paging(null, e);
  }

  /**
   * 排序
   * event 排序字段与规则
   */
  public sort(field) {
    if (this.rule === 'asc') {
      this.rule = 'desc';
    } else if (this.rule === 'desc') {
      this.rule = '';
    } else {
      this.rule = 'asc';
    }
    this.tableFindModel.sort(field, this.rule);
  }

  public search(event, table) {
    this.tableFindModel.formInfo[table.field] = event;
  }

}
